﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace TuyennvLibrary.Notify.Android
{
    public class AndroidNotify
    {
        public string Uri { get; set; }
        public object Data { get; set; }
        public string ApiKey { get; set; }
        public string CollapseKey { get; set; }
        public bool DelayWhileIdle { get; set; }
        public List<string> RegistrationIds { get; set; }
        public AndroidNotify()
        {
            Uri = "https://android.googleapis.com/gcm/send";
            CollapseKey = "score_update";
            DelayWhileIdle = true;
            ApiKey = "";
            Data = new object();
            this.RegistrationIds = new List<string>();
        }
        public AndroidNotifyResponse Push()
        {
            AndroidNotifyResponse notifyResponse = new AndroidNotifyResponse();
            try
            {
                if (string.IsNullOrEmpty(ApiKey))
                    throw new Exception("ApiKey Empty");
                var json = new
                {
                    collapse_key = CollapseKey,
                    delay_while_idle = DelayWhileIdle,
                    data = new
                    {
                        payload = Data
                    },
                    registration_ids = RegistrationIds
                };
                string jsondata = JsonConvert.SerializeObject(json);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri);
                request.Method = "POST";
                request.KeepAlive = false;
                byte[] byteArray = Encoding.UTF8.GetBytes(jsondata);
                request.ContentType = "application/json";
                request.ContentLength = byteArray.Length;
                request.Headers.Add(HttpRequestHeader.Authorization, "key=" + ApiKey);

                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string responsedata = reader.ReadToEnd();
                reader.Close();
                object mResponse = JsonConvert.DeserializeObject(responsedata);
                notifyResponse.RegistrationIds = RegistrationIds;
                notifyResponse.Response = responsedata;
                notifyResponse.Analytics();

            }
            catch (Exception ex)
            {
                notifyResponse.AddFailure();
            }
            return notifyResponse;
        }
    }
}
